<?php
require_once dirname(__FILE__) . '/includes/common.inc.php';
require_once dirname(__FILE__) . "/database/$database/database.inc.php";
  
header('Content-Type: text/plain');

$q = json_decode(MiscUtils::getParam('q', NULL));


try {
  $hostname = HOST_NAME;
  $username = USER_NAME;
  $password = PASSWORD;
  $dbname = DATABASE_NAME;
  $myPdo = new PDO ('mysql:host=' . $hostname, $username, $password);
  $myPdo->exec('USE ' . $dbname);
  $myPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
  echo $e->getMessage ();
}

try {
  $myPdo->beginTransaction ();
  foreach ($q as &$tmp) {
    $orm = classToOrm($tmp->n);
    if ($orm) {
      foreach ($tmp->a as &$obj) {
        if (isset($obj->e_oid) || isset($obj->id)) {
//          MiscUtils::dump(MiscUtils::obj2Upd($orm->dto, $obj));
          $myPdo->exec(MiscUtils::obj2Upd($orm->dto, $obj));
        } else {
//          MiscUtils::dump(MiscUtils::obj2Ins($orm->dto, $obj));
          $myPdo->exec(MiscUtils::obj2Ins($orm->dto, $obj));
        }
      }
      foreach ($tmp->r as &$obj) {
//        MiscUtils::dump(MiscUtils::obj2Del($orm->dto, $obj));
        $myPdo->exec(MiscUtils::obj2Del($orm->dto, $obj));
      }
    }
  }
  $myPdo->commit ();
  echo json_encode(array());
} catch (PDOException $e) {
  $myPdo->rollBack();
  echo MiscUtils::encode($e->getMessage());
}
?>